import { MySeriveProvider } from './../my-serive/my-serive';
/**
 * Create by zihan on 2018-03-15
-*/
import { Injectable } from '@angular/core';
import { HttpSeriveProvider } from '../http-serive/http-serive';
import { FileTransfer, FileUploadOptions, FileTransferObject } from "@ionic-native/file-transfer";

// import { BASE_URL } from '../constants';

@Injectable()
export class UploadApi {
  headers;
  constructor(
    private httpService: HttpSeriveProvider,
    private transfer: FileTransfer,
    private mySeriveProvider:MySeriveProvider
  ) {
    this.headers = this.mySeriveProvider.headers;
  }

  // BASEURL = 'http://120.78.237.154:8080' + '/ucenter';
  // BASEURL = 'http://120.78.237.154:8080/photo/test';
  BASEURL = 'http://120.78.237.154:8080/photo/upload';
  // upload(assetUrl, bucketType = 'UserBucket', fileName?, file?): Promise<any> {
  //   return new Promise((resolve, reject) => {
  //   this.httpService.post('http://120.78.237.154:8080/photo/upload', assetUrl)
  //     .subscribe((data) => {
  //       resolve(data)
  //     }, (err) => {
  //       reject(err)
  //     })
  //   })
  // }

  //裁剪完成之后上传图片文件 new
  uploadImage(assetUrl, bucketType = 'UserBucket', fileName?, file?): Promise<any> {
    
    return new Promise((resolve, reject) => {
      //如果在真机运行 支持FileTransfer
      if (FileTransfer['installed']()) { 
        let options: FileUploadOptions = {
          fileKey: "uploadPhoto",
          fileName: "pcAvatar.jpg", //文件名称
          mimeType: "multipart/form-data",
          // fileKey: 'file',
          // fileName: fileName || 'pic.jpg',
          headers: {}
        };
        const fileTransfer: FileTransferObject = this.transfer.create()
        // fileTransfer.onProgress(progress => {
        //   console.log('fileTransfer.onProgress')
        //   console.log(progress)
        // }) 
        
        fileTransfer.upload(assetUrl, this.BASEURL, options)
          .then(result => {
            const data = JSON.parse(result.response)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
      } else if (file) {
        // if not support FileTransfer, use html file upload
        //网页运行
        //如果是base64格式，转file
         
        if (/^(data:)/.test(assetUrl)) {
          file = this.convertBase64UrlToBlob(assetUrl)
        }
        let fileName = file.name || '';
        if (!fileName) fileName = Date.now() + '.' + (file.type).match(/\/(.*)/)[1];
        let formData: FormData = new FormData();
        formData.append('uploadPhoto', file, fileName);
        this.httpService.post(this.BASEURL, formData)
          .subscribe((data) => {            
            resolve(data)
          }, (err) => {
            reject(err) 
          }) 
      } else {
        reject({msg: '没有图片可以上传'})
        // console.log('没有图片可以上传');
      }
    })
  }


  //dataURItoBlob这个方法转的话不能成功，我就换了一种方法
  convertBase64UrlToBlob(urlData){  
      var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte  
      //处理异常,将ascii码小于0的转换为大于0  
      var ab = new ArrayBuffer(bytes.length);  
      var ia = new Uint8Array(ab);  
      for (var i = 0; i < bytes.length; i++) {  
          ia[i] = bytes.charCodeAt(i);  
      }   
      return new Blob( [ab] , {type : 'image/png'});  
  } 
 
  // base64 图片转file Blob
  dataURItoBlob(dataURI) {
    const
      byteString = atob(dataURI.split(',')[1])
      , mimeString = dataURI.split(',')[0].match(/:([^;]*)/)[1]
      , ab = new ArrayBuffer(byteString.length) //ArrayBuffer 对象用来表示通用的、固定长度的原始二进制数据缓冲区。
      , ia = new Uint8Array(ab)//Uint8Array表示的8位无符号整数数组。内容初始化为0。虽然我也不懂

    for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    console.log(dataURI);
    console.log(mimeString);
    console.log({ type: mimeString });
    
    return new Blob([ab], { type: mimeString });
  }

}